package com.yuexiao.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yuexiao.entity.ResultInfo;
import com.yuexiao.pojo.Dish;
import com.yuexiao.pojo.ShoppingCart;
import com.yuexiao.service.DishService;
import com.yuexiao.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName:ShoppingCartController
 * @Auther: YUEXIAO
 * @Description: TODO
 * @Date: 2022/8/13 16:59
 * @Version: v1.0
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Reference
    private ShoppingCartService shoppingCartService;


    /**
     * 查询登录用户购物车的列表
     * @param request 无需手动传入
     * @return ResultInfo 返回结果对象
     */
    @GetMapping("/cartList")
    @PreAuthorize("hasAnyRole('ROLE_NOMAL')")
    public ResultInfo cartList(HttpServletRequest request){
        //从session中获取用户id
        Object userid = request.getSession().getAttribute("userid");
        if(userid==null){
            return  ResultInfo.error("用户未登录");
        }
        return ResultInfo.success(shoppingCartService.getShoppingCartListByUserId((Long) userid));
    }

    /**
     * 新增购物车记录
     * @param shoppingCart ShoppingCart 购物车实体对象
     * @return ResultInfo 返回结果对象
     */
    @PostMapping("/addShoppingCart")
    @PreAuthorize("hasAnyRole('ROLE_NOMAL')")
    public ResultInfo addShoppingCart(@RequestBody ShoppingCart shoppingCart){
        return ResultInfo.success(shoppingCartService.insertShopping(shoppingCart));
    }


    /**
     * 减少商品数量
     * @param shoppingCart ShoppingCart 购物车实体对象
     * @return ResultInfo 返回结果对象
     */
    @PostMapping("/subCart")
    @PreAuthorize("hasAnyRole('ROLE_NOMAL')")
    public ResultInfo subCart(@RequestBody ShoppingCart shoppingCart){
        return ResultInfo.success(shoppingCartService.updateShoppingCartByDishIdOrSetmealId(shoppingCart));
    }


    /**
     * 清空购物车
     * @param request 无需手动传入
     * @return ResultInfo返回结果对象
     */
    @DeleteMapping("/clearCart")
    @PreAuthorize("hasAnyRole('ROLE_NOMAL')")
    public ResultInfo clearCart(HttpServletRequest request){
        //从session中获取用户id
        Object userid = request.getSession().getAttribute("userid");
        if(userid==null){
            return  ResultInfo.error("用户未登录");
        }
        return ResultInfo.success(shoppingCartService.deleteShoppingCartByUserId(Long.valueOf(String.valueOf(userid))));
    }


}
